package com.ccl.keyassistant.activity;
/*
 *项目名     FingerprintTest
 *包名       com.ccl.fingerprinttest
 *文件名     LoginActivity
 *创建者     ccl
 *创建时间   2019-03-14 20:18
 *注解       指纹识别类
 */

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.os.Bundle;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyProperties;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.ccl.keyassistant.MainActivity;
import com.ccl.keyassistant.R;
import com.ccl.keyassistant.db.DBDataHelper;
import com.ccl.keyassistant.entity.BaseModel;
import com.ccl.keyassistant.entity.Pin;
import com.ccl.keyassistant.fragment.FingerprintPinCodeDialogFragment;
import com.ccl.keyassistant.fragment.PinCodeDialogFragment;
import com.ccl.keyassistant.utils.L;
import com.ccl.keyassistant.utils.PermissionUtil;
import com.ccl.keyassistant.utils.StaticClass;
import com.ccl.keyassistant.view.CustomDialog;

import java.security.KeyStore;
import java.util.ArrayList;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String DEFAULT_KEY_NAME = "default_key";

    KeyStore keyStore;
    private Button finger;
    private Button pincode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        getWritePermission();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        initView();
        /**
         * 设置pincode
         * 使用pincode进行认证
         * 1 从数据库中读取pincode
         * 2 如果pincode为空，则要求输入pincode
         */
        DBDataHelper dataHelper = DBDataHelper.getInstance(getApplicationContext());
        ArrayList<BaseModel> pincode = dataHelper.select("pincode", " pincode ",
                null, null, null, Pin.class);

        //未查询到PIN，设置PIN
        if (pincode.size() == 0) {
            //设置PIN
            showPinCodeDialog(StaticClass.PINCODE_STORAGE);
        } else {
            if (supportFingerprint()) {
                this.pincode.setVisibility(View.GONE);
                initKey();
                initCipher();
            } else {
                finger.setVisibility(View.GONE);
                showPinCodeDialog(StaticClass.PINCODE_CHECK);
            }
        }
    }

    /**
     * 获取存储空间的读写权限
     */
    private void getWritePermission() {
        if (!PermissionUtil.isPermitted(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            PermissionUtil.requestPermission(LoginActivity.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, StaticClass.PERMISSION_STORAGE);
        }
    }

    /**
     * 权限处理回调函数
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            //读写权限
            case StaticClass.PERMISSION_STORAGE: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //成功获取权限
                    Toast.makeText(this, "读写权限获取成功", Toast.LENGTH_SHORT).show();
                } else {
                    //未获取权限
                    final CustomDialog dialog = new CustomDialog(this, R.layout.custom_dialog_ok);
                    dialog.show();

                    //利用inflate方式获取控件的点击事件是不生效的
//                    View view = View.inflate(this, R.layout.custom_dialog_ok, null);
                    //利用此方法可以
                    dialog.getWindow().findViewById(R.id.custom_dialog_ok).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            L.i("click");
                            dialog.dismiss();
                            PermissionUtil.requestPermission(LoginActivity.this,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, StaticClass.PERMISSION_STORAGE);
                        }
                    });
                }
                return;
            }
            default:
                break;

        }
    }


    private void initView() {
        finger = (Button) findViewById(R.id.login_finger);
        pincode = (Button) findViewById(R.id.login_pincode);

        finger.setOnClickListener(this);
        pincode.setOnClickListener(this);
    }

    public boolean supportFingerprint() {
        if (Build.VERSION.SDK_INT < 23) {
            Toast.makeText(this, "您的系统版本过低，不支持指纹功能", Toast.LENGTH_SHORT)
                    .show();
            return false;
        } else {
            KeyguardManager keyguardManager = getSystemService(KeyguardManager.class);
            FingerprintManager fingerprintManager = getSystemService(FingerprintManager.class);
            if (!fingerprintManager.isHardwareDetected()) {
                Toast.makeText(this, "您的手机不支持指纹功能", Toast.LENGTH_SHORT).show();
                return false;
            } else if (!keyguardManager.isKeyguardSecure()) {
                Toast.makeText(this, "您还未设置锁屏，请先设置锁屏并添加一个指纹",
                        Toast.LENGTH_SHORT).show();
                return false;
            } else if (!fingerprintManager.hasEnrolledFingerprints()) {
                Toast.makeText(this, "您至少需要在系统设置中添加一个指纹",
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        return true;
    }

    @TargetApi(23)
    private void initKey() {
        try {
            keyStore = KeyStore.getInstance("AndroidKeyStore");
            keyStore.load(null);
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(DEFAULT_KEY_NAME,
                    KeyProperties.PURPOSE_ENCRYPT |
                            KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
            keyGenerator.init(builder.build());
            keyGenerator.generateKey();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @TargetApi(23)
    private void initCipher() {
        try {
            SecretKey key = (SecretKey) keyStore.getKey(DEFAULT_KEY_NAME, null);
            Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + KeyProperties.BLOCK_MODE_CBC + "/"
                    + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            showFingerPrintPinCodeDialog(cipher);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //显示指纹和pin
    private void showFingerPrintPinCodeDialog(Cipher cipher) {
        FingerprintPinCodeDialogFragment fragment = new FingerprintPinCodeDialogFragment();
        fragment.setCipher(cipher);
        fragment.setCancelable(false);
        fragment.show(getFragmentManager(), "fingerprint");
    }

    //只显示pin
    private void showPinCodeDialog(boolean mode) {
        PinCodeDialogFragment fragment = new PinCodeDialogFragment();
        fragment.setMode(mode);
        fragment.setCancelable(false);
        fragment.show(getFragmentManager(), "pincode");
    }

    //指纹验证成功后，通过传入的activity在fragment中调用此方法
    public void onAuthenticated() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_finger:
                //调取指纹验证
                initKey();
                initCipher();
                break;
            case R.id.login_pincode:
                showPinCodeDialog(StaticClass.PINCODE_CHECK);
                break;
        }
    }
}